package com.wwj.aicodemother.core.handler;

import com.wwj.aicodemother.model.entity.User;
import com.wwj.aicodemother.model.enums.ChatHistoryMessageTypeEnum;
import com.wwj.aicodemother.service.ChatHistoryService;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;

/**
 * 简单文本流处理器
 * 处理HTML,MULTi_FILE流式响应
 */
@Slf4j
public class SimpleTextStreamHandler {

    /**
     * 处理传统流(HTML,MULTi_FILE)
     *
     * @param originStream       原始流
     * @param chatHistoryService 对话历史服务
     * @param appId              应用id
     * @param loginUser          登录用户
     * @return  处理后的流
     */
    public Flux<String> handle(Flux<String> originStream,
                               ChatHistoryService chatHistoryService,
                               long appId, User loginUser) {
        StringBuilder aiResponseBuilde = new StringBuilder();
        return originStream.map(chuck -> {
            aiResponseBuilde.append(chuck);
            return chuck;
        }).doOnComplete(() -> {
            //流式返回完成，保存AI消息到对话历史中
            chatHistoryService.addChatMessage(appId, aiResponseBuilde.toString(), ChatHistoryMessageTypeEnum.AI.getValue(), loginUser.getId());
        }).doOnError(error -> {
            //如果AI生成失败也需要保存
            chatHistoryService.addChatMessage(appId, error.getMessage(), ChatHistoryMessageTypeEnum.AI.getValue(), loginUser.getId());
        });
    }
}
